'use client'

import { useEffect, useMemo, useState } from 'react'
import { Button } from '@/components/ui/button'
import type { Agent } from '@/types/agent'
import { Label } from '@/components/ui/label'
import { Input } from '@/components/ui/input'
import { Textarea } from '@/components/ui/textarea'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group'
import { Checkbox } from '@/components/ui/checkbox'
import { useToast } from '@/hooks/use-toast'

interface AgentFormPanelProps {
  agent?: Agent | null
  disabled?: boolean
  onSend: (content: string) => void
}

export function AgentFormPanel({ agent, disabled, onSend }: AgentFormPanelProps) {
  const isFormEnabled = Boolean(agent?.isFormEnabled)
  const rawFormConfig = agent?.formJson
  const { toast } = useToast()

  const formConfig = useMemo(() => {
    if (!rawFormConfig) return { fields: [] as any[] }
    try {
      const parsed = typeof rawFormConfig === 'string' ? JSON.parse(rawFormConfig) : rawFormConfig
      const fields = Array.isArray(parsed) ? parsed : (parsed?.fields ?? [])
      return { fields: Array.isArray(fields) ? fields : [] }
    } catch (e) {
      console.warn('解析 agent.formJson 失败:', e)
      return { fields: [] as any[] }
    }
  }, [rawFormConfig])

  const [formValues, setFormValues] = useState<Record<string, any>>({})

  useEffect(() => {
    const initial: Record<string, any> = {}
    formConfig.fields.forEach((f: any) => {
      const key = f.label || ''
      if (!key) return
      switch (f.type) {
        case 'checkbox':
          initial[key] = Array.isArray(f.defaultValue) ? f.defaultValue : []
          break
        default:
          initial[key] = typeof f.defaultValue === 'string' ? f.defaultValue : ''
      }
    })
    setFormValues(initial)
  }, [formConfig])

  const updateFormValue = (label: string, value: any) => {
    setFormValues(prev => ({ ...prev, [label]: value }))
  }

  const buildFormMessage = () => {
    const lines: string[] = []
    formConfig.fields.forEach((f: any) => {
      const key = f.label || ''
      if (!key) return
      const val = formValues[key]
      if (val == null) return
      const display = Array.isArray(val) ? val.join(',') : String(val)
      // 过滤空字符串或空数组
      if (display.trim().length === 0) return
      lines.push(`${key}：${display};`)
    })
    return lines.join('\n')
  }

  if (!isFormEnabled || formConfig.fields.length === 0) {
    return null
  }

  return (
    <aside className="hidden md:flex w-[360px] shrink-0 border-l border-blue-200 bg-white flex-col">
      <div className="p-4 border-b">
        <div className="text-sm text-gray-500">表单</div>
        <div className="text-base font-semibold text-gray-800">{agent?.name || '配置表单'}</div>
      </div>
      <div className="flex-1 overflow-y-auto p-4 space-y-4">
        {formConfig.fields.map((f: any, idx: number) => (
          <div key={idx} className="space-y-2">
            <label className="block text-sm font-medium text-gray-700">{f.label}</label>
            {f.type === 'text' && (
              <Input
                className="w-full"
                placeholder={f.placeholder || ''}
                value={formValues[f.label] ?? ''}
                onChange={(e) => updateFormValue(f.label, e.target.value)}
              />
            )}
            {f.type === 'textarea' && (
              <Textarea
                className="w-full"
                placeholder={f.placeholder || ''}
                rows={4}
                value={formValues[f.label] ?? ''}
                onChange={(e) => updateFormValue(f.label, e.target.value)}
              />
            )}
            {f.type === 'select' && !Boolean(f.multiple) && (
              <Select
                value={(formValues[f.label] ?? '') as string}
                onValueChange={(v) => updateFormValue(f.label, v)}
              >
                <SelectTrigger className="w-full">
                  <SelectValue placeholder={f.placeholder || '请选择'} />
                </SelectTrigger>
                <SelectContent>
                  {(f.options || []).map((opt: any, i: number) => (
                    <SelectItem key={i} value={opt.value}>{opt.label}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
            )}
            {f.type === 'select' && Boolean(f.multiple) && (
              <div className="rounded border bg-white p-2 space-y-2">
                {(f.options || []).map((opt: any, i: number) => {
                  const arr: any[] = Array.isArray(formValues[f.label]) ? formValues[f.label] : []
                  const checked = arr.includes(opt.value)
                  return (
                    <label key={i} className="flex items-center gap-2 text-sm">
                      <Checkbox
                        checked={checked}
                        onCheckedChange={(val: boolean) => {
                          const next = new Set(arr)
                          if (val) next.add(opt.value)
                          else next.delete(opt.value)
                          updateFormValue(f.label, Array.from(next))
                        }}
                      />
                      <span>{opt.label}</span>
                    </label>
                  )
                })}
              </div>
            )}
            {f.type === 'radio' && (
              <RadioGroup
                value={(formValues[f.label] ?? '') as string}
                onValueChange={(v) => updateFormValue(f.label, v)}
                className="space-y-2"
              >
                {(f.options || []).map((opt: any, i: number) => (
                  <div key={i} className="flex items-center gap-2">
                    <RadioGroupItem id={`radio-${idx}-${i}`} value={opt.value} />
                    <Label htmlFor={`radio-${idx}-${i}`}>{opt.label}</Label>
                  </div>
                ))}
              </RadioGroup>
            )}
            {f.type === 'checkbox' && (
              <div className="space-y-2">
                {(f.options || []).map((opt: any, i: number) => {
                  const arr: any[] = Array.isArray(formValues[f.label]) ? formValues[f.label] : []
                  const checked = arr.includes(opt.value)
                  return (
                    <label key={i} className="flex items-center gap-2 text-sm">
                      <Checkbox
                        checked={checked}
                        onCheckedChange={(val: boolean) => {
                          const next = new Set(arr)
                          if (val) next.add(opt.value)
                          else next.delete(opt.value)
                          updateFormValue(f.label, Array.from(next))
                        }}
                      />
                      <span>{opt.label}</span>
                    </label>
                  )
                })}
              </div>
            )}
          </div>
        ))}
      </div>
      <div className="p-4 border-t">
        <Button
          className="w-full"
          disabled={disabled}
          onClick={() => {
            const content = buildFormMessage()
            if (content.trim().length === 0) {
              toast({
                title: '未填写内容',
                description: '请至少填写一项表单字段后再发送。',
              })
              return
            }
            onSend(content)
          }}
        >
          发送表单内容
        </Button>
      </div>
    </aside>
  )
}